package com.apestech.framework.sql.variable;

import com.apestech.framework.json.JSONArray;
import com.apestech.framework.sql.modul.SqlList;
import com.apestech.framework.sql.modul.VarList;
import com.apestech.framework.util.StringUtil;

/**
 * 获取SQL执行相关信息
 * @author hupo
 *
 */
public class SqlCase extends StringUtil{

	public class SqlItem{
		private String sql;
		private String execSql;
		private String printSql;

		public SqlItem(String sql, String execSql, String printSql){
			this.sql=sql;
			this.execSql=execSql;
			this.printSql=printSql;
		}

		public String getSql() {
			return sql;
		}

		public String getExecSql() {
			return execSql;
		}

		public String getPrintSql() {
			return printSql;
		}
	}

	private SqlList param;
	private String execSql="";
	private String printSql="";
	private String sql="";
	private JSONArray paramList=new JSONArray();
	private SqlInfo sqlinfo;

	public SqlCase(SqlList param, String dbType, String sqlType) throws Exception{
		this.param=param;
		this.sqlinfo=new SqlInfo(dbType, sqlType);
	}

	public JSONArray getParamList(){
		return this.paramList;
	}
	
	public void add(SqlList param) throws Exception{
		int size=this.param.size();
		this.param.add(param);
		expain(size);
	}

	public void expain() throws Exception{
		expain(0);
	}
	
	private void expain(int index) throws Exception{
		int len=this.param.size();
		for(int i=index; i<len; i++){
			VarList v=this.param.get(i);
			SqlItem in=setSqlValue(v);
			if(in!=null){
				this.execSql=this.execSql+in.getExecSql();
				this.printSql=this.printSql+in.getPrintSql();
				this.sql=this.sql+in.getSql();
			}
		}
	}
	
	private SqlItem setSqlValue(VarList v) throws Exception{
		if(v==null) return null;
		String text=v.getText();
		String execText="";
		String printText="";
        if(!"".equals(text)){
			int len=v.size();
			for(int i=0; i<len; i++){
				sqlinfo.setExecSql(execText);
				sqlinfo.setPrintSql(printText);
				sqlinfo.setParamList(paramList);
				sqlinfo.expain(text, v.get(i), i==len-1);
				execText=sqlinfo.getExecSql();
				printText=sqlinfo.getPrintSql();
				paramList=sqlinfo.getParamList();
			}
			if(len==0){
				execText=text;
				printText=text;
			}
			return new SqlItem(text, execText, printText);
		}
		return null;
	}
	
	public String getExecSql(){
		if(!"".equals(this.sql) && "".equals(this.execSql)){
			this.execSql=this.sql;
		}
		return this.execSql;
	}
	
	public String getPrintSql(){
		if(!"".equals(this.sql) && "".equals(this.printSql)){
			this.printSql=this.sql;
		}
		return this.printSql;
	}
	
	public String toString(){
		StringBuilder sb=new StringBuilder();
		sb.append("sql : "+this.sql+"\n");
		sb.append("execSql : "+getExecSql()+"\n");
		sb.append("printSql : "+getPrintSql()+"\n");
		sb.append("params : "+this.paramList.toString());
		return sb.toString();
	}

}
